package cn.itzd.utils;

import cn.itzd.entity.LoginUser;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public class SecurityUtils {

    /**
     * 获取用户
     **/
    public static LoginUser getLoginUser() {
        Authentication authentication = getAuthentication();
        if (ObjectUtils.isEmpty(authentication)) {
            return new LoginUser();
        }
        Object principal = authentication.getPrincipal();
        if (principal instanceof String || ObjectUtils.isEmpty(principal)) {
            return new LoginUser();
        }
        return (LoginUser) principal;
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }


    public static Long getUserId() {
        return ObjectUtils.isEmpty(getLoginUser().getId()) ? 0L : getLoginUser().getId();
    }
}
